package br.fiap.backbean;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

@ManagedBean(name = "data")
public class Data {

    private int dia, mes, ano;

    public int getAno() {
        return ano;
    }

    public void setAno(int ano) {
        this.ano = ano;
    }

    public int getDia() {
        return dia;
    }

    public void setDia(int dia) {
        this.dia = dia;
    }

    public int getMes() {
        return mes;
    }

    public void setMes(int mes) {
        this.mes = mes;
    }

    public void validarData(ComponentSystemEvent event) {
        UIComponent source = event.getComponent();
        
        UIInput diaInput = (UIInput) source.findComponent("dia");
        UIInput mesInput = (UIInput) source.findComponent("mes");
        UIInput anoInput = (UIInput) source.findComponent("ano");

        int d = ((Integer) diaInput.getLocalValue()).intValue();
        int m = ((Integer) mesInput.getLocalValue()).intValue();
        int a = ((Integer) anoInput.getLocalValue()).intValue();
        
        FacesMessage message = new FacesMessage("Data valida!");
        if (!isDataValida(d, m, a)) {
            message = new FacesMessage("Data invalida!");
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
        }
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(source.getClientId(), message);
        context.renderResponse();
    }

    public boolean isDataValida(int dia, int mes, int ano) {
        boolean valida = false;
        if (ano >= 0) {
            if (mes >= 1 && mes <= 12) {
                if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12) {
                    if (dia <= 31) {
                        valida = true;
                    } else {
                        if (mes != 2) {
                            if (dia <= 30) {
                                valida = true;
                            }
                        } else {
                            if (ano % 4 == 0) {
                                if (dia <= 29) {
                                    valida = true;
                                } 
                            } else {
                                if (dia <= 28) {
                                    valida = true;
                                }
                            }
                        }
                    }
                }
            }
        }
        return valida;
    }
}
